package com.cloudeye.logtest.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by lafangyuan on 2020/12/31.
 */
@Slf4j
public class ConnectServerHandler extends ChannelInboundHandlerAdapter {

    private int MAX_HEART_BEAT = 3;
    private int heatBeatTime = 0;
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("server channelRegistered：{}",ctx.channel().id());
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("server channelUnregistered：{}",ctx.channel().id());
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("server channelActive：{}",ctx.channel().id());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("server channelInactive：{}",ctx.channel().id());
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("server channelRead：{},{}",ctx.channel().id(),msg);
        heatBeatTime=0;
        super.channelRead(ctx, msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("server userEventTriggered：{}",ctx.channel().id());
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if(IdleState.READER_IDLE.equals(event.state())){
                log.info("没有收到消息...");
                heatBeatTime++;
            }
            if(heatBeatTime==MAX_HEART_BEAT){
                ctx.channel().close();
            }
        }else{
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("server exceptionCaught：{}",ctx.channel().id());
        super.exceptionCaught(ctx, cause);
    }
}
